<template>
    <!-- 报警事件管理  -->
    <div class="content_div">
        <div class="content_top">
            <div class="content_title">系统管理 / <span style="color: var(--buttonDeep-color)">出入类型配置管理</span></div>
            <i class="sprite-diagonal-bar"></i>
        </div>
        <div class="content_top" style="justify-content: space-between">
            <div class="dis_flex">
                <div class="content_title">出入类型配置列表</div>
                <i class="sprite-diagonal-bar"></i>
            </div>
            <div class="con_tit" @click="springFrame()"><i class="sprite-List-related-added"></i> 新增</div>
        </div>
        <div style="height: calc(100% - 10rem);">
            <el-table
                class="customer-table"
                :data="tableData"
                tooltip-effect="dark"
                ref="multipleSelection"
                v-loading="tableLoading"
                element-loading-background="var(--eleTableHover)"
                height="100%"
                style="width: 100%; background-color: transparent"
                @selection-change="handleSelectionChange"
            >
                <el-table-column header-align="center" align="center" type="index" label="序号" width="80"> </el-table-column>
                <el-table-column prop="name" label="出入配置名称" show-overflow-tooltip> </el-table-column>
                <el-table-column prop="deviceCount" label="关联设备数"> </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <div style="display: flex">
                            <el-tooltip class="item" effect="dark" content="查看" placement="top-start">
                                <div class="sprite-List-related-watch" @click="handleWatch(scope.row)" style="cursor: pointer"></div>
                            </el-tooltip>
                            <el-tooltip class="item" effect="dark" content="修改" placement="top-start">
                                <div
                                    class="sprite-List-related-update"
                                    @click="edit(scope.row)"
                                    style="margin-left: 10px; cursor: pointer"
                                ></div>
                            </el-tooltip>
                            <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
                                <div
                                    class="sprite-List-related-delete-table"
                                    @click="delRow(scope.row, tableData)"
                                    style="margin-left: 10px; cursor: pointer"
                                ></div>
                            </el-tooltip>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="paging div-pagination">
            <el-pagination
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :page-size="queryParams.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :page-sizes="[10, 30, 60, 90, 100]"
                :total="totalCount"
            ></el-pagination>
        </div>
        <!-- 查看 -->
        <el-dialog
            :visible.sync="watchDialog"
            width="60%"
            :before-close="beforeClosed"
            class="dialog-doubleColumn"
            title="查看出入类型配置"
            :close-on-click-modal="false"
            :modal-append-to-body="false"
        >
            <el-form :model="formDataWatch" label-width="150px" ref="form">
                <el-form-item label="出入记录类型名称" style="width: 100%">
                    <el-input readonly v-model="formDataWatch.name" placeholder=""></el-input>
                </el-form-item>
                <!-- <el-form-item label="校区" style="width: 100%">
                    <el-input readonly v-model="formDataWatch.campusName" placeholder=""></el-input>
                </el-form-item> -->
                <el-form-item label="选择设备" style="width: 100%" prop="campusList">
                    <el-tree v-if="isRouterAlive" :props="props" :data="treeData" ref="tree-info" 
                    :default-checked-keys="infoDefaultCheckedKeys"
                    node-key="id" show-checkbox readonly @check-change="handleCheckChange"> </el-tree>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="beforeClosed" class="dialog-footer-resetBtn">取 消</el-button>
            </div>
        </el-dialog>
        <!-- 新增  编辑 -->
        <el-dialog
            :visible.sync="dialogVisible"
            width="60%"
            :before-close="beforeClosed"
            class="dialog-doubleColumn"
            :title="formTit"
            :close-on-click-modal="false"
            :modal-append-to-body="false"
        >
            <el-form :model="formData" label-width="150px" ref="form" :rules="rules">
                <el-form-item label="出入记录类型名称" style="width: 100%" prop="name">
                    <el-input placeholder="请输入出入记录类型" clearable v-model.trim="formData.name"> </el-input>
                </el-form-item>
                <!-- <el-form-item label="选择校区" style="width: 100%" prop="campusId">
                    <el-select
                        v-model="formData.campusId"
                        placeholder="请选择校区"
                        popper-class="selectPopprt"
                        class="div-small-select"
                        style="width: 100%; background-color: none !important; border: none"
                        @change="campusChange"
                    >
                        <el-option v-for="(item, index) in options.campusListOptions" :key="index" :label="item.label" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item> -->
                <el-form-item label="选择设备" style="width: 100%" prop="campusList">
                    <el-tree v-if="isRouterAlive" :props="props" :data="treeData" ref="tree" node-key="id" :default-checked-keys="infoDefaultCheckedKeys" show-checkbox @check-change="handleCheckChange">
                    </el-tree>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="beforeClosed" class="dialog-footer-resetBtn">取 消</el-button>
                <el-button class="dialog-footer-sureBtn" v-preventReClick @click="submitForm">保存</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import api from '../../api/systemManagement/accessTypeCon';
import optionsMixin from '../../mixins/optionsMixin';
const bfBase = 'bf' // bf
const rBase = 'r' // r
export default {
    mixins: [optionsMixin],
    // components:{XCampusBuilrRoom},
    data() {
        return {
            // 条件
            queryParams: {
                pageSize: 10,
                pageNum: 1
            },
            options: {
                campusListOptions: []
            },
            // 列表
            tableData: [],
            treeData: [],
            tableLoading: false,
            totalCount: 0,
            rules: {
                name: [{ required: true, message: '请输入出入类型配置', trigger: 'blur' }],
                campusId: [{ required: true, message: '请选择校区', trigger: 'blur' }],
                campusList: [{ required: true, message: '请选择设备', trigger: 'blur' }]
            },
            dialogVisible: false,
            watchDialog: false,
            formData: {},
            formDataWatch: {},
            formTit: '',
            // // 树形控件
            props: {
                children: 'children',
                label: 'name'
            },
            count: 1,
            isRouterAlive: true,
            treeToList: [],
            infoDefaultCheckedKeys: []
        };
    },
    created() {
        this.getList();
        this.campusChange();
    },
    methods: {
        campusChange(value, is, isBase = true) {
                // 树形结构接口
            api.getCampusBuildFloorRoom({}).then((res) => {
                console.log('11111111111',res)
                
                const campusList = res.data.campusList;
                if (campusList && campusList.length > 0) {
                    this.handleTree(campusList, 0, is, 0, isBase)
                    this.treeToList = []
                    this.handleTreeToList(JSON.parse(JSON.stringify(campusList)), this.treeToList, 0);
                    if(is) {
                        const list = JSON.parse(JSON.stringify(this.treeToList))
                        const infoDefaultList = list
                            .filter(item => this.infoDefaultCheckedKeys.find(it => it == item.id))
                        console.log('this.infoDefaultList', this.treeToList, infoDefaultList)
                        infoDefaultList.push(...JSON.parse(JSON.stringify(campusList)))
                        this.treeData = this.handleListToTree(infoDefaultList, 0, 0)
                        console.log('this.treeData', this.treeData)
                    } else {
                        this.treeData = campusList;

                    }
                }
                this.reload();
            });
        },
        handleTreeToList(tree, list, level) {
            level += 1;
            tree.forEach(item => {
                if(item.children && item.children.length > 0) {
                    this.handleTreeToList(item.children, list, level);
                }
                item.children = []
                item.level = level
                list.push(item)
            })
        },
        handleTree(list, id, is, level, isBase) {
            level += 1;
            list.forEach(item => {
                if(isBase && level == 3) {
                    item.id = bfBase + item.id
                } else if(!isBase && level == 3) {
                    if(item.id.indexOf(bfBase) == 0) {
                        item.id = item.id.substring(bfBase.length)
                    }                    
                }
                if(isBase && level == 4) {
                    item.id = rBase + item.id
                } else if(!isBase && level == 4) {
                    if(item.id.indexOf(rBase) == 0) {
                        item.id = item.id.substring(rBase.length)
                    }                    
                }
                item.pId = id
                item.disabled = is
                item.level = level
                
                if(item.children && item.children.length > 0) {
                    this.handleTree(item.children, item.id, is, level, isBase);
                }
            })
        },
        reload() {
            this.isRouterAlive = false;
            this.$nextTick(function () {
                this.isRouterAlive = true;
            });
        },
        getList() {
            api.list(this.queryParams).then((res) => {
                this.tableData = res.data.records;
                this.totalCount = res.data.total;
            });
            // api.campusList({}).then((res) => {
            //     this.options.campusListOptions = res.data.map((item) => ({
            //         ...item,
            //         label: item.name,
            //         value: item.id
            //     }));
            // });
        },
        // 树形控件
        handleCheckChange() {
            const checkTree = this.$refs.tree.getCheckedNodes()
            const list = JSON.parse(JSON.stringify(checkTree))
            this.handleCheckTree(list)
            this.formData.campusList = this.handleListToTree(list, 0, 0)
            console.log('this.formData.campusList', this.formData.campusList)
            
        },
        handleListToTree(list, pId, level) {
            level += 1;
            const tree = []
            list.forEach(item => {
                if(item.pId == pId && item.level == level) {
                    let temp = this.handleListToTree(list, item.id, level)
                    if(temp.length > 0) {
                        item.children = temp
                    }
                    tree.push(item)
                }
                // if(item.pId == pId && level == item.level) {
                //     arr.push(item)
                //     const children = this.handleListToTree(list, item.id, level);
                //     children.length && (item.children = children)
                // }
            })
            return tree
        },
        handleCheckTree(list) {
            for (let index = 0; index < list.length; index++) {
                const item = list[index];
                // 清空 children
                if(item.children && item.children.length > 0) {
                    item.children = []
                }
                // 查找父级
                if(!list.find(it => it.id == item.pId)) {
                    // 没有父级元素则补充
                    const fItem = this.treeToList.find(it => it.id == item.pId  && it.level == item.level - 1)
                    if(fItem){
                        list.push(fItem)
                        if(!list.find(it => it.id == fItem.pId)) {
                            const fItem2 = this.treeToList.find(it => it.id == fItem.pId && it.level == fItem.level - 1)
                            if(fItem2){
                                list.push(fItem2)
                            }
                        }

                    }
                }
            }
        },
        handleNodeClick(data) {
            console.log(data);
        },
        // 查看
        handleWatch(row) {
            this.watchDialog = true;
            api.info(row.id).then((data) => {
                console.log('`````````data', data);
                this.formDataWatch = data.data;
                this.infoDefaultCheckedKeys.push(
                    ...this.formDataWatch.buildingList.map(item => item.buildingId),
                    ...this.formDataWatch.buildingList.map(item => bfBase + item.buildingFloorId),
                    ...this.formDataWatch.buildingList.map(item => rBase + item.roomId)
                )
                this.infoDefaultCheckedKeys = Array.from(new Set(this.infoDefaultCheckedKeys))
                this.campusChange(this.formDataWatch.campusId, true)
            });
        },
        // 新增
        springFrame() {
            this.formTit = '新增出入类型配置';
            this.campusChange()
            this.dialogVisible = true;
        },
        // 修改
        edit(row) {
            this.formTit = '修改出入类型配置';
            this.dialogVisible = true;
            const id = row.id || this.ids;
            api.info(id).then((data) => {
                this.formData = data.data;
                this.formData.buildingList.forEach(item => {
                    if(item.roomId){this.infoDefaultCheckedKeys.push(rBase + item.roomId)}
                    else if(item.buildingFloorId){this.infoDefaultCheckedKeys.push(bfBase + item.buildingFloorId)}
                    else if(item.buildingId){this.infoDefaultCheckedKeys.push(item.buildingId)}
                })
                this.infoDefaultCheckedKeys = Array.from(new Set(this.infoDefaultCheckedKeys))
                this.campusChange(this.formData.campusId, false)
                this.formLoading = false;
            });
        },
        // 保存
        submitForm() {
            this.handleCheckChange()
            if(this.formData && this.formData.campusList && this.formData.campusList.length == 0){
                this.$message({
                    type: 'error',
                    message: '设备必填!'
                });
                return false;
            }
            this.$refs.form.validate((valid) => {
                if (!valid) return false;
                this.handleTree(this.formData.campusList, 0, false, 0, false)
                // await this.campusChange(this.formDataWatch.campusId, false, false)

                if (this.formData.id != null) {
                    api.update(this.formData).then((response) => {
                        console.log(response);
                        this.$message({
                            type: 'success',
                            message: '操作成功!'
                        });
                        this.dialogVisible = false;
                        this.getList();
                        this.beforeClosed()

                        this.reload()
                    });
                } else {
                    api.add({
                        ...this.formData
                    }).then((response) => {
                        console.log(response);
                        this.$message({
                            type: 'success',
                            message: '操作成功!'
                        });
                        this.dialogVisible = false;
                        this.getList();
                        this.beforeClosed()

                        this.reload()
                    });
                }
            });
        },
        // 删除
        delRow(row) {
            this.$confirm('是否删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                api.del(row.id).then((data) => {
                    console.log(data);
                    this.getList();
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                });
            });
        },
        // 弹框--取消按钮，清空表单
        beforeClosed() {
            this.dialogVisible = false;
            this.watchDialog = false;
            this.formData = {
                name: ''
            };
            this.infoDefaultCheckedKeys = []
            this.treeData = []
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        handleSizeChange(val) {
            this.queryParams.pageSize = val;
            // this.getList();
        },
        handleCurrentChange(val) {
            this.queryParams.pageNum = val;
            // this.getList();
        }
    }
};
</script>
<style lang="scss" scoped>
/deep/ .el-tree {
    background: var(--eleInput-bgcolor);
    .el-tree-node__content {
        background: var(--eleTheme-color);
    }
    .el-tree-node__content:hover {
        background: var(--eleTheme-color);
    }
}
.con_tit {
    width: 88px;
    height: 32px;
    background: rgba(47, 225, 255, 0);
    border-radius: 4px;
    border: 1px solid var(--buttonDeep-color);
    font-size: 14px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: var(--buttonDeep-color);
    align-items: center;
    justify-content: center;
    display: flex;
    cursor: pointer;
    float: right;
    margin-right: 30px;
}
</style>
